<?php
	class CaijiAction extends CommonAction{
		public function index(){
			
			$this->assign('pagename','所有采集规则');
			//$this->assign('checkcaiji',' active');
			
			$cj=M('Caiji');
			$count=$cj->count();
			
			import('ORG.UTIL.Page');
			
			$page=new Page($count,10);
			$pageshow=$page->show();
			$pageshow=str_replace('<a ','<a class="btn btn-primary" ',$pageshow);
			$this->assign('pageshow',$pageshow);
			
			$cjArr=$cj->limit($page->firstRow.','.$page->listRows)->order('id desc')->select();
			
			/*foreach($cjArr as $cja){
				//查询所属小说
				$N=M('Novel');
				$novelinfo=$N->field('novelname')->find($cja['novelid']);
				//查询分卷名称
				$V=M('Vol');
				$volinfo=$V->field('volname')->find($cja['novelvolid']);
				//$cjinfos[]=array_merge(array('novelname'=>$novelinfo['novelname'],'volname'=>$volinfo['volname']),$cja);
				$cjinfos[]=array_merge($novelinfo,$volinfo,$cja);
			}
			*/
			$this->assign('cjinfos',$cjArr);
			$this->display();
		
		}
		protected function getUrlContent($url) {
			
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL,$url);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl,  CURLOPT_CUSTOMREQUEST, 'GET');//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); 
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
		}		
		
				//单本书采集
		public function caijias($caijiid=''){
			echo '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>';
			$caijiInfo['caijiurl']='https://www.zwdu.com/book/';
			if(!isset($_GET['pageid'])){		
				//取对方的章节及内容
				$caijiInfo['caijiid']=$caijiid;
				$oneurl=$caijiInfo['caijiurl'].$caijiInfo['caijiid'].'/';
				$content=$this->getUrlContent($oneurl);
				$content=mb_convert_encoding($content , "UTF-8", "GBK"); 
				$find=false;
				$articlenamereu='/<h1>(.*)<\/h1>/U';
				preg_match_all($articlenamereu,$content,$articlename);
				
				$articleauthorreu='/<p>作&nbsp;&nbsp;&nbsp;&nbsp;者：(.*)<\/p>/Us';
				preg_match_all($articleauthorreu,$content,$author);
			
				$articlestatusreu='/<p>状&nbsp;&nbsp;&nbsp;&nbsp;态：(.*)<\/p>/Us';
				preg_match_all($articleauthorreu,$content,$status);
				$articlestatus = explode(',',$status[1][0]);
				
				//return;
			
				$articleintroreu='/<div id="intro">(.*)<\/div>/Us';
				preg_match_all($articleintroreu,$content,$intro);

				$Article=M('article_article');
				$where['articlename']=$articlename[1][0];
				$return=$Article->where($where)->field('articleid')->select();
				if(empty($return)){
				$slq['articlename']=$articlename[1][0];
				$slq['author']=$author[1][0];
				$slq['intro']=$intro[1][0];
				$slq['poster']='admin';
				$slq['caijiid']=$caijiid;
			
				$return=$Article->add($slq);
				
				}
				var_dump($return);
				$return=$Article->where($where)->field('articleid')->select();
				$chatper='C:\www\wwwroot\txt\\'.$return[0]['articleid'];
				if(!file_exists($path)){
					mkdir($chatper,0777,true);//这个是在c盘根目录生成文件
				}
				//采集封面图片
				$imgdri='/<img alt="(.*)" src="(.*)" width="120" height="150" onerror="(.*)">/Us';
				
				if(preg_match($imgdri,$content,$img)){
				
				$fileurl='C:\www\wwwroot\img\\'.$return[0]['articleid'];
				if(!file_exists($path)){
					mkdir($fileurl,0777,true);//这个是在c盘根目录生成文件
				}
				$image = file_get_contents($img[2]); 
				file_put_contents($fileurl.'\image.jpg', $image); //保存图片到本地地址
				}else{
					echo "<h1>图片匹配不成功!</h1>";
					exit();
				}
				$jieqi_article=M('article_article');
				$where_lastchapter['caijiid']=$caijiid;
				$lastchapter=$jieqi_article->where($where_lastchapter)->getField('lastchapter');

				$reu='/<dd><a href="(.*).html">(.*)<\/a><\/dd>/U';
				if(preg_match_all($reu,$content,$conArr)){
					
					$i=0;
					foreach($conArr[2] as $conInfo){
						if($find){
							$nextName=$conInfo;
							break;
						}
						//echo $conInfo."------".$lastchapter.'<br>';
						if($conInfo == $lastchapter){
							$find=true;
						}
						if(strstr($lastchapter,$conInfo)){
							$find=true;
						}
						$i=$i+1;
					}
					
					if($find == false){
						$i=0;
					}
					
				//var_dump('hahaha');
					if($conArr[1][$i]){	
						$articleid = explode('/',$conArr[1][$i]); 
						
						
						$this->success('分析成功对方章节，即将采集！',U('Caiji/caijias/')."/id/".$return[0]['articleid']."/pageid".$conArr[1][$i]."/bookid/".$articleid[2]."/articleid/".$articleid[3]."/return/".$return[0]['articleid']);
						//跳转采集
					}else{
						 echo "<h1>采集完毕！</h1>";
						 $a='<h1>采集完毕！</h1>';
						break;
					}
				}else{
					echo "<h1>出现错误，传参错误！匹配失败！</h1>";
				}
			}else{
				
				$oneurl=$caijiInfo['caijiurl'].$_GET['bookid'].'/';
				$caijiurl=$oneurl.$_GET['articleid'].".html";
				
				$content=$this->getUrlContent($caijiurl);
				$content=mb_convert_encoding($content , "UTF-8", "GBK");
				$reutitle='/<h1>(.*)<\/h1>/';
				if(preg_match($reutitle,$content,$titles)){
					$title=trim($titles[1]);
					
				}else{
					echo "<h1>标题匹配不成功!</h1>";exit();
				}
				$reucontent='/<div id="content">(.*)<\/div>/Us';
				
				if(preg_match($reucontent,$content,$con)){
					$novelcon=trim($con[1]);
					$novelcon=str_ireplace("jiyou.com",'',$novelcon);
					$novelcon=str_ireplace("集阅小说网",'',$novelcon);
				}else{
					echo "<h1>内容匹配不成功!</h1>";exit();
				}		
				//入库
				$C=M('Content');
				$where='`con_nid`='.$_GET['return'].' and `con_name` LIKE "'.$title.'"';
				$haveThis=$C->where($where)->find();
				if(!is_array($haveThis)){
					$addInfo['con_nid']=$_GET['return'];
					$addInfo['con_name']=$title;
					$insert=$C->add($addInfo);
					$fileid=$_GET['articleid'];
					$fileurl='C:\www\wwwroot\txt\\'.$_GET['return'].'\\'.$fileid.'.txt';
					$myfile = fopen($fileurl, "a") or die("Unable to open file!");//这个是在c盘根目录生成文件
					fwrite($myfile, $novelcon);
					
					if($insert==false){
						echo "<h1>".$addInfo['con_name']."本条记录插入失败</h1>";exit();
					}
					$cj=M('Caiji');
					$lastchaptercondision['caijiid']=$_GET['bookid'];
					$last_chapter_data = array('lastchapterid'=>$fileid,'lastchapter'=>$title);
					 $result = $cj->where($lastchaptercondision)->setField($last_chapter_data);
					 $jieqi=M('article_article');
					 $jieqilastchapter=$jieqi->where($lastchaptercondision)->setField($last_chapter_data);
					
				}	
				//匹配下一页
				$nextpage='/<div class="bottem1">(.*)<\/div>/Us';
				if(preg_match($nextpage,$content,$nexts)){
					$pat = '/<a href="(.*)">(.*)<\/a>/U';
					preg_match_all($pat, $nexts[1], $m);

					$next=$m[1][2];
					$nextid=str_ireplace(".html","",trim($next));
					$articleid = explode('/',$nextid); 
					//var_dump($nextid);
					$order_nextid="/book/".$articleid[2]."/";
					//var_dump($order_nextid);
					if($nextid==$order_nextid){
						//echo "<h1>采集已经完成！</h1>";
						$a="<h1>采集已经完成！</h1>";
						return $a;
					}
					
				}else{
					echo "<h1>下一章ID匹配不成功!</h1>";
					exit();
				}
				$nextUrl=U('Caiji/caijias/')."/id/".$_GET['id']."/pageid/".$nextid."/bookid/".$articleid[2]."/articleid/".$articleid[3]."/return/".$_GET['return'];
				
				//还要更新时间
				$N=M('Novel');
				$novelin['update_time']=time();
				$novelin['id']=$caijiInfo['novelid'];
				$N->save($novelin);
				//跳转到下一条
				$this->success($title." 采集成功，即将跳转到下一章",$nextUrl,1);
				
			}
		}
		
		//采集单本小说
		public function caiji(){	
			$this->caijias($_GET['id']);
			return $a;
		}
		//采集多本小说
		public function manycaiji(){
			$manyid=$_GET['id'];
			$manyids = substr($manyid,0,strlen($manyid)-1); 
			$manyid = explode(",", $manyids);
			for($i=0;$i<count($manyids);$i++){
				//echo $manyid[$i];
				
				$a=$this->caijias($manyid[$i]);
			echo $a;
				
			}
			//foreach($manyid as $key=>$value){
		//pclose($this->caijias($value));
		//var_dump($value);
		//}
		}
		//采集网站所有小说名称
	/*	public function allcaiji(){
			
		//	echo '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>';
			//$url="https://www.zwdu.com/";
			//取对方的小说
			$lists=array();
			for($i=7598; $i<7600; $i++){
				$b=$this->caijias($i);
				if($b)
				
				}
	
			}*/
		

		
		
		public function del(){
			$CJ=M('Caiji');
			$where['id']=$_GET['id'];
			$isDel=$CJ->where($where)->delete();
			if($isDel){
				$this->success('删除成功！',U('Caiji/index'));
			}else{
				$this->error('删除失败！');
			
			}
		}
		
		//批量删除采集规则操作
		public function delMany(){
			$m=M('Caiji');
			$idArr=trim($_GET['id'],',');
			$where='id in ('.$idArr.')';
			$delstate=$m->where($where)->delete();
			if($delstate > 0){
				$this->success('删除采集规则成功！',U('Caiji/index'));
			}else{
				$this->error('删除采集规则失败！',U('Caiji/index'));
			}
		}
		
		
		public function add(){
			$this->assign('pagename','添加采集规则');
			$this->assign('checkcaiji',' active');
			$this->display();
		}
		public function addcaiji(){
			if(isset($_POST['caijiid']) and $_POST['caijiid'] != null ){
				
					$cjinfo['caijiid']=$_POST['caijiid'];
			
			
			}else{
				$this->error('小说ID不能为空！');
			}
			
			if(isset($_POST['caijiname']) and $_POST['caijiname'] != null ){
				$cjinfo['caijiname']=$_POST['caijiname'];
			}else{
				$this->error('本条规则不能为空！');
			}
			
			if($_POST['caijiurl'] != null ){
				if(preg_match('/\w+/',$_POST['caijiurl']) == false){
					$this->error('对方小说URL应该为字母或者数字！');
				}
				$cjinfo['caijiurl']=$_POST['caijiurl'];
			}else{
				$this->error('对方小说URL不能为空！');
			}
			$caiji=M('Caiji');
			$isInsert=$caiji->add($cjinfo);
			if($isInsert){
				$this->success('添加规则成功！');
			}else{
				$this->error('添加规则失败！');
			}
		}
	
	}

?>